package com.ocom.jobhandler.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.dto.TimerPaymentCallBackDto;
import com.ocom.common.entity.access.EntityMjRegionInfo;
import com.ocom.common.entity.company.EntityComDockApi;
import com.ocom.common.entity.master.EntityYkmCenterConfig;
import com.ocom.common.entity.payconfig.EntityXfMerchMoneyDay;
import com.ocom.common.request.company.GetApiListRequest;
import com.ocom.common.request.exposeapi.boczhxy.AuthenticationRequest;
import com.ocom.common.request.exposeapi.boczhxy.TranInfo;
import com.ocom.common.request.payconfig.SubsidyListRequest;
import com.ocom.common.request.payconfig.setConsMerchPayReportsRequest;
import com.ocom.common.request.simple.AllPersonRequest;
import com.ocom.common.request.simple.MqTimerRequest;
import com.ocom.common.request.simple.kcmz.KCMZConsumeRecordRequest;
import com.ocom.common.request.simple.ssgl.SSGLAccessRecordRequest;
import com.ocom.common.request.simple.ssgl.SSGLAttendanceRecordRequest;
import com.ocom.common.request.simple.ssgl.SSGLNewPersonInfoRequest;
import com.ocom.common.request.web.CommonPidVo;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.resp.Result;
import com.ocom.common.response.web.SubsidyListResponse;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.vo.GrantSubsidyVo;
import com.ocom.common.vo.accessdevice.CenterMachInfoVo;
import com.ocom.common.vo.simple.ConsumeDetailVo;
import com.ocom.jobhandler.feign.*;
import com.ocom.redis.util.RedisUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * XxlJob开发示例（Bean模式）
 * <p>
 * 开发步骤：
 * 1、任务开发：在Spring Bean实例中，开发Job方法；
 * 2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 * 4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
public class SampleXxlJob {
    private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);

    @Autowired
    private SrvpAccessFeignService srvpAccessFeignService;

    @Autowired
    private AccessClientService accessClientService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private PayoperFeignService payoperFeignService;

    @Autowired
    private PayConfigClientService payConfigClientService;

    @Autowired
    private CompanyClientService companyClientService;

    @Autowired
    private MqSubsidyClientService maPayClientService;

    @Autowired
    private MqSimpleClientService mqSimpleClientService;

    @Autowired
    private ExposeapiClientService exposeapiClientService;

    @Autowired
    private HumanClientService humanClientService;

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("demoJobHandler")
    public void demoJobHandler() throws Exception {
        XxlJobHelper.log("定时任务开始");
        for (int i = 0; i < 5; i++) {
            XxlJobHelper.log("beat at:" + i);
            TimeUnit.SECONDS.sleep(2);
        }
        XxlJobHelper.handleFail("定时任务有问题");
    }


    @XxlJob("getCenterTaskByTime")
    public void getCenterTaskByTime() throws Exception {
        XxlJobHelper.log("获取中台定时任务开始");
        Date now = new Date();
        String h1 = String.format("%02d", DateUtil.getHour(now));
        Integer minute = DateUtil.getMinute(now);
        minute = minute >= 30 ? 30 : 0;
        String m1 = String.format("%02d", minute);
        String strTime = h1 + ":" + m1;
        RespMachMessage yMjYkmMessage = srvpAccessFeignService.getMJMkm(strTime);
        if (yMjYkmMessage.getCode().equals("0000")) {
            XxlJobHelper.log("获取主库的中台定时任务:" + JSON.toJSONString(yMjYkmMessage));
            List<EntityYkmCenterConfig> entityMjYkmList = JSON.parseArray(JSON.toJSONString(yMjYkmMessage.getData()), EntityYkmCenterConfig.class);
            for (EntityYkmCenterConfig entityMjYkm : entityMjYkmList) {
                //判断缓存是否已存在该keyunicomcomId #horTime #regionId};存在则执行下次循环，不存在则继续执行；
                String horTimeRedis = entityMjYkm.getComId() + ":" + strTime + ":" + entityMjYkm.getRegionId();
                if (redisUtil.lock(horTimeRedis, 60 * 60)) {
                    //2.单位调用羊城通日上限数Nums; 调用接口getCommNumsByComId( comId)
                    Result numsMessage = accessClientService.getCommNumsByComId(entityMjYkm.getComId());
                    if (numsMessage.getCode() == 200) {

                        CenterMachInfoVo centerMachInfoVo = JSON.parseObject(JSON.toJSONString(numsMessage.getData()), CenterMachInfoVo.class);

                        if (entityMjYkm.getRegionId() == 0l) {
                            Result getCenterTaskOfYkmResult = accessClientService.getCenterTaskOfYkm(entityMjYkm.getComId(), entityMjYkm.getRegionId(), 0L, centerMachInfoVo.getTimesAll());
                            if (getCenterTaskOfYkmResult.getCode() != 200) {
                                XxlJobHelper.log("获取人员身份信息入redis:" + JSON.toJSONString(getCenterTaskOfYkmResult));
                            }
                            continue;
                        }


                        JSONObject deptIdJSONObject = new JSONObject();
                        deptIdJSONObject.put("comId", entityMjYkm.getComId());
                        deptIdJSONObject.put("regionId", entityMjYkm.getRegionId());
                        Result srvpaccessResult = accessClientService.getRegionInfo(deptIdJSONObject);
                        if (srvpaccessResult.getCode() == 200) {
                            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(srvpaccessResult.getData()));
                            List<EntityMjRegionInfo> entityMjRegionInfoList = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), EntityMjRegionInfo.class);
                            if (entityMjRegionInfoList.size() > 0) {
                                for (EntityMjRegionInfo entityMjRegionInfo : entityMjRegionInfoList) {
                                    Result getCenterTaskOfYkmResult = accessClientService.getCenterTaskOfYkm(entityMjYkm.getComId(), entityMjYkm.getRegionId(), entityMjRegionInfo.getDeptId(), centerMachInfoVo.getTimesAll());
                                    if (getCenterTaskOfYkmResult.getCode() != 200) {
                                        XxlJobHelper.log("获取人员身份信息入redis:" + JSON.toJSONString(getCenterTaskOfYkmResult));
                                    }
                                }
                            } else {
                                Result getCenterTaskOfYkmResult = accessClientService.getCenterTaskOfYkm(entityMjYkm.getComId(), entityMjYkm.getRegionId(), Long.valueOf(-1), centerMachInfoVo.getTimesAll());
                                if (getCenterTaskOfYkmResult.getCode() != 200) {
                                    XxlJobHelper.log("获取人员身份信息入redis:" + JSON.toJSONString(getCenterTaskOfYkmResult));
                                }
                            }
                        } else if (srvpaccessResult.getCode() == 1001) {
                            Result getCenterTaskOfYkmResult = accessClientService.getCenterTaskOfYkm(entityMjYkm.getComId(), entityMjYkm.getRegionId(), 0L, centerMachInfoVo.getTimesAll());
                            if (getCenterTaskOfYkmResult.getCode() != 200) {
                                XxlJobHelper.log("获取人员身份信息入redis:" + JSON.toJSONString(getCenterTaskOfYkmResult));
                            }
                        } else {
                            XxlJobHelper.log("获取拉取最大数量失败:" + JSON.toJSONString(srvpaccessResult));
                        }
                    } else {
                        XxlJobHelper.log("单位调用羊城通日上限数:" + JSON.toJSONString(numsMessage));
                    }
                } else {
                    XxlJobHelper.log("这个单位的这个时间的定时任务已执行," + JSON.toJSONString(yMjYkmMessage));
                }
            }
        } else {
            XxlJobHelper.handleFail("获取主库的中台定时任务:" + JSON.toJSONString(yMjYkmMessage));
        }
    }

    //定时任务处理支付中的订单
    @XxlJob("paymentTiming")
    public ReturnT<String> paymentTiming() throws Exception {
        String param = XxlJobHelper.getJobParam();
        XxlJobHelper.log("定时任务paymentTiming处理支付中的订单的任务开始，参数"+param);
        payoperFeignService.paymentTiming(Integer.valueOf(param));
        XxlJobHelper.log("定时任务ABCpaymentTiming处理支付中的订单的任务结束");
        return ReturnT.SUCCESS;
    }

    //定时任务处理支付中的订单
    @XxlJob("ABCpaymentTiming")
    public ReturnT<String> ABCpaymentTiming() throws Exception {
        XxlJobHelper.log("定时任务ABCpaymentTiming处理支付中的订单的任务开始");
        payoperFeignService.ABCPaymentTimings();
        XxlJobHelper.log("定时任务ABCpaymentTiming处理支付中的订单的任务结束");
        return ReturnT.SUCCESS;
    }

    //定时任务处理门禁设备
    @XxlJob("MjAlarmSend")
    public ReturnT<String> MjAlarmSend() throws Exception {
        XxlJobHelper.log("定时任务MjAlarmSend的任务开始");
        payConfigClientService.mjAlarmSend(1L);
        payConfigClientService.mjAlarmSend(501L);
        XxlJobHelper.log("定时任务MjAlarmSend的任务结束");
        return ReturnT.SUCCESS;
    }

    //定时查询未推送记录
    @XxlJob("timerRequestApi")
    public void timerRequestApi() throws Exception {
        String param = XxlJobHelper.getJobParam();
        XxlJobHelper.log("定时查询未推送记录的任务开始");
        GetApiListRequest request = new GetApiListRequest();
        if (!CommonUtil.isNull(param)) {
            request.setDockApiCode(param);
        }
        Result result = companyClientService.getApiList(request);
        if (200 == result.getCode()) {
            List<EntityComDockApi> list = JSON.parseArray(JSON.toJSONString(result.getData()), EntityComDockApi.class);
            for (EntityComDockApi entityComDockApi : list) {
                try {

                    switch (entityComDockApi.getDockApiCode()) {
                        case "zkzl#paymentCallBack":
                            XxlJobHelper.log("中卡智磊定时查询未推送记录任务开始");
                            payoperFeignService.zkzlTimerPaymentCallBack(new TimerPaymentCallBackDto());
                            XxlJobHelper.log("中卡智磊定时查询未推送记录任务结束");
                            break;
                        case "ssgl#newPersonInfo":
                            XxlJobHelper.log("宿管协议-推送人员信息任务开始");
                            SSGLNewPersonInfoRequest newPersonInfoRequest = new SSGLNewPersonInfoRequest();
                            newPersonInfoRequest.setComId(entityComDockApi.getComId());
                            mqSimpleClientService.ssglMqNewPersonInfo(newPersonInfoRequest);
                            XxlJobHelper.log("宿管协议-推送人员信息任务结束");
                            break;
                        case "ssgl#accessRecord":
                            XxlJobHelper.log("宿管协议-推送门禁记录任务开始");
                            SSGLAccessRecordRequest accessRecordRequest = new SSGLAccessRecordRequest();
                            accessRecordRequest.setComId(entityComDockApi.getComId());
                            mqSimpleClientService.ssglMqAccessRecord(accessRecordRequest);
                            XxlJobHelper.log("宿管协议-推送门禁记录任务结束");
                            break;

                        case "ccbzhsh#newPersonInfo":
                            XxlJobHelper.log("建行智慧生活-同步用户信息任务开始");
                            SSGLNewPersonInfoRequest personInfoRequest = new SSGLNewPersonInfoRequest();
                            personInfoRequest.setComId(entityComDockApi.getComId());
                            mqSimpleClientService.ccbZHSHMQNewPersonInfo(personInfoRequest);
                            XxlJobHelper.log("建行智慧生活-同步用户信息任务结束");
                            break;
                        case "wgkq#newPersonInfo":
                            XxlJobHelper.log("无感考勤-推送人员信息任务开始");
                            SSGLNewPersonInfoRequest wgkqNewPersonInfoRequest = new SSGLNewPersonInfoRequest();
                            wgkqNewPersonInfoRequest.setComId(entityComDockApi.getComId());
                            mqSimpleClientService.wgkqMqNewPersonInfo(wgkqNewPersonInfoRequest);
                            XxlJobHelper.log("无感考勤-推送人员信息任务结束");
                            break;

                        case "kcmzct#consumeRecord":
                            XxlJobHelper.log("柯城民政老来伴-订单上报任务开始");
                            KCMZConsumeRecordRequest consumeRecordRequest = new KCMZConsumeRecordRequest();
                            consumeRecordRequest.setComId(entityComDockApi.getComId());
                            mqSimpleClientService.kcmzctMqConsumeRecord(consumeRecordRequest);
                            XxlJobHelper.log("柯城民政老来伴-订单上报任务结束");
                            break;

                        case "unicom#consEvent":
                            XxlJobHelper.log("联通平台-设备数据上报接口");
                            MqTimerRequest mqTimerRequest = new MqTimerRequest();
                            mqTimerRequest.setComId(entityComDockApi.getComId());
                            mqTimerRequest.setAutoSize(entityComDockApi.getAutoSize());
                            mqSimpleClientService.unicomMqConsEvent(mqTimerRequest);
                            XxlJobHelper.log("联通平台-设备数据上报接口");
                            break;

                        case "unicom#updateAccType":
                            XxlJobHelper.log("联通平台-更改用户消费类型 :"+entityComDockApi.getComId());
                            CommonPidVo commonPidVo=new CommonPidVo();
                            commonPidVo.setComId(entityComDockApi.getComId());
                            mqSimpleClientService.updateAccType(commonPidVo);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        XxlJobHelper.log("定时查询未推送记录的任务结束");
    }

    @XxlJob("ocomkqTimedPush")
    public void ocomkqTimedPush() throws Exception {
        XxlJobHelper.log("ocomkqTimedPush-定时查询未推送记录的任务开始");
        GetApiListRequest request = new GetApiListRequest();
        request.setDockCode("ocomkq");
        Result result = companyClientService.getApiList(request);
        if (200 == result.getCode()) {
            List<EntityComDockApi> list = JSON.parseArray(JSON.toJSONString(result.getData()), EntityComDockApi.class);
            for (EntityComDockApi entityComDockApi : list) {
                try {

                    switch (entityComDockApi.getDockApiCode()) {
                        case "ocomkq#newPersonInfo":
                            XxlJobHelper.log("Ocom考勤平台-推送人员信息任务开始");
                            SSGLNewPersonInfoRequest newPersonInfoRequest = new SSGLNewPersonInfoRequest();
                            newPersonInfoRequest.setComId(entityComDockApi.getComId());
                            mqSimpleClientService.ocomKqMqNewPersonInfo(newPersonInfoRequest);
                            XxlJobHelper.log("Ocom考勤平台-推送人员信息任务结束");
                            break;

                        case "ocomkq#attendanceRecord":
                            XxlJobHelper.log("Ocom考勤平台-定时推送考勤记录");
                            SSGLAttendanceRecordRequest attendanceRecordRequest = new SSGLAttendanceRecordRequest();
                            attendanceRecordRequest.setComId(entityComDockApi.getComId());
                            mqSimpleClientService.ocomKqAttendanceRecord(attendanceRecordRequest);
                            XxlJobHelper.log("Ocom考勤平台-定时推送考勤记录");
                            break;


                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        XxlJobHelper.log("定时查询未推送记录的任务结束");
    }

    @XxlJob("accountBalance")
    public void accountBalance() throws Exception {
        XxlJobHelper.log("上月结余的任务开始");
        payConfigClientService.accountBalance();
        XxlJobHelper.log("上月结余的任务结束");
    }

    /**
     * @Description:定时发放补贴
     * @author lu
     * @date 2022/12/8 14:12
     */

    @XxlJob("SubsidyTimerGrant")
    public void SubsidyTimerGrant() throws Exception {
        XxlJobHelper.log("补贴发放的任务开始");
        String month = DateUtils.getLastMonth();
        Result subsidyListResult= payConfigClientService.subsidyComIdList(100l,month);
        if(subsidyListResult.getCode()==200 && subsidyListResult.getData()!=null){
            List<Long> comIds =JSON.parseArray(JSON.toJSONString(subsidyListResult.getData()),Long.class);
            if(comIds.size()>0) subsidyHandle(comIds);
        }
        Result subsidyListResult2= payConfigClientService.subsidyComIdList(600l,month);
        if(subsidyListResult2.getCode()==200 && subsidyListResult2.getData()!=null){
            List<Long> comIds =JSON.parseArray(JSON.toJSONString(subsidyListResult2.getData()),Long.class);
            if(comIds.size()>0) subsidyHandle(comIds);
        }
        XxlJobHelper.log("补贴发放的任务结束");
    }


    private void subsidyHandle(List<Long> comIds) {
        for (Long comId : comIds) {
            SubsidyListRequest subsidyListRequest = new SubsidyListRequest();
            subsidyListRequest.setComId(comId);

            String month = DateUtils.getLastMonth();
            subsidyListRequest.setBeginMonth(month);
            subsidyListRequest.setStrStatus("2");
            subsidyListRequest.setSize(500);
            subsidyListRequest.setPage(1);
            subsidyListRequest.setSortType(2);
            Result subsidyListResultOne = payConfigClientService.subsidyList(subsidyListRequest);

            if (subsidyListResultOne.getCode() != 200) {
                XxlJobHelper.log("定时发放补贴获取补贴计划列表失败,单位:" + comId);
                return;
            }
            ConsumeDetailVo subsidyListRecordsOne = JSON.parseObject(JSON.toJSONString(subsidyListResultOne.getData()), ConsumeDetailVo.class);
            for (Object subsidyList : subsidyListRecordsOne.getList()) {
                try {
                    SubsidyListResponse subsidyListResponse = JSON.parseObject(JSON.toJSONString(subsidyList), SubsidyListResponse.class);
                    String newDate = DateUtil.getStrDate(new Date(), "yyyy-MM-dd");
                    if (subsidyListResponse.getPlanDate() == null) {
                        continue;
                    }
                    if (subsidyListResponse.getPlanDate().compareTo(newDate) <= 0) {
                        GrantSubsidyVo grantSubsidyVo = new GrantSubsidyVo();
                        grantSubsidyVo.setComId(comId);
                        grantSubsidyVo.setTimes(subsidyListResponse.getTimes());
                        grantSubsidyVo.setMonth(subsidyListResponse.getMonth());
                        maPayClientService.grantSubsidy(grantSubsidyVo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 2、分片广播任务
     */
    @XxlJob("shardingJobHandler")
    public void shardingJobHandler() throws Exception {

        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();

        XxlJobHelper.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);

        // 业务逻辑
        for (int i = 0; i < shardTotal; i++) {
            if (i == shardIndex) {
                XxlJobHelper.log("第 {} 片, 命中分片开始处理", i);
            } else {
                XxlJobHelper.log("第 {} 片, 忽略", i);
            }
        }

    }


    /**
     * 3、命令行任务
     */
    @XxlJob("commandJobHandler")
    public void commandJobHandler() throws Exception {
        String command = XxlJobHelper.getJobParam();
        int exitValue = -1;

        BufferedReader bufferedReader = null;
        try {
            // command process
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command(command);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();
            //Process process = Runtime.getRuntime().exec(command);

            BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
            bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));

            // command log
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                XxlJobHelper.log(line);
            }

            // command exit
            process.waitFor();
            exitValue = process.exitValue();
        } catch (Exception e) {
            XxlJobHelper.log(e);
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }

        if (exitValue == 0) {
            // default success
        } else {
            XxlJobHelper.handleFail("command exit value(" + exitValue + ") is failed");
        }

    }


    /**
     * 4、跨平台Http任务
     * 参数示例：
     * "url: http://www.baidu.com\n" +
     * "method: get\n" +
     * "data: content\n";
     */
    @XxlJob("httpJobHandler")
    public void httpJobHandler() throws Exception {

        // param parse
        String param = XxlJobHelper.getJobParam();
        if (param == null || param.trim().length() == 0) {
            XxlJobHelper.log("param[" + param + "] invalid.");

            XxlJobHelper.handleFail();
            return;
        }

        String[] httpParams = param.split("\n");
        String url = null;
        String method = null;
        String data = null;
        for (String httpParam : httpParams) {
            if (httpParam.startsWith("url:")) {
                url = httpParam.substring(httpParam.indexOf("url:") + 4).trim();
            }
            if (httpParam.startsWith("method:")) {
                method = httpParam.substring(httpParam.indexOf("method:") + 7).trim().toUpperCase();
            }
            if (httpParam.startsWith("data:")) {
                data = httpParam.substring(httpParam.indexOf("data:") + 5).trim();
            }
        }

        // param valid
        if (url == null || url.trim().length() == 0) {
            XxlJobHelper.log("url[" + url + "] invalid.");

            XxlJobHelper.handleFail();
            return;
        }
        if (method == null || !Arrays.asList("GET", "POST").contains(method)) {
            XxlJobHelper.log("method[" + method + "] invalid.");

            XxlJobHelper.handleFail();
            return;
        }
        boolean isPostMethod = method.equals("POST");

        // request
        HttpURLConnection connection = null;
        BufferedReader bufferedReader = null;
        try {
            // connection
            URL realUrl = new URL(url);
            connection = (HttpURLConnection) realUrl.openConnection();

            // connection setting
            connection.setRequestMethod(method);
            connection.setDoOutput(isPostMethod);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setReadTimeout(5 * 1000);
            connection.setConnectTimeout(3 * 1000);
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");

            // do connection
            connection.connect();

            // data
            if (isPostMethod && data != null && data.trim().length() > 0) {
                DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
                dataOutputStream.write(data.getBytes("UTF-8"));
                dataOutputStream.flush();
                dataOutputStream.close();
            }

            // valid StatusCode
            int statusCode = connection.getResponseCode();
            if (statusCode != 200) {
                throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
            }

            // result
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            String responseMsg = result.toString();

            XxlJobHelper.log(responseMsg);

            return;
        } catch (Exception e) {
            XxlJobHelper.log(e);

            XxlJobHelper.handleFail();
            return;
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (Exception e2) {
                XxlJobHelper.log(e2);
            }
        }

    }

    /**
     * 5、生命周期任务示例：任务初始化与销毁时，支持自定义相关逻辑；
     */
    @XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
    public void demoJobHandler2() throws Exception {
        XxlJobHelper.log("XXL-JOB, Hello World.");
    }

    //9.3.1补缴定时短信通知（RepairPayPage/timedSMS）
    @XxlJob("repairPayPageTimedSMS")
    public void repairPayPageTimedSMS() throws Exception {
        XxlJobHelper.log("补缴定时短信通知的任务开始");
        payConfigClientService.repairPayPageTimedSMS();
        XxlJobHelper.log("补缴定时短信通知的任务结束");
    }

    //9.3.2补缴状态定时查询（RepairPayPage/updatePayStatus）
    @XxlJob("repairPayPageUpdatePayStatus")
    public void repairPayPageUpdatePayStatus() throws Exception {
        XxlJobHelper.log("补缴状态定时查询的任务开始");
        payConfigClientService.repairPayPageUpdatePayStatus(1L);
        payConfigClientService.repairPayPageUpdatePayStatus(501L);
        XxlJobHelper.log("补缴状态定时查询的任务结束");
    }


    //7.4.8定时终止过期消费券（CouponsVoucher/timerStop）
    @XxlJob("couponsVoucherTimerStop")
    public void couponsVoucherTimerStop() throws Exception {
        XxlJobHelper.log("定时终止过期消费券的任务开始");
        payConfigClientService.couponsVoucherTimerStop(1L);
        payConfigClientService.couponsVoucherTimerStop(501L);
        XxlJobHelper.log("定时终止过期消费券的任务结束");
    }




    @XxlJob("autoconfirmTrace")
    public void autoconfirmTrace(){
        String paramStr = XxlJobHelper.getJobParam();

        JSONObject jsonObject = JSON.parseObject(paramStr);

        String param = jsonObject.getString("comId");

        XxlJobHelper.log("定时任务autoconfirmTrace处理每天自动分账的任务开始，参数"+param);

        //获取前一天时间
        LocalDate currentDate = LocalDate.now();
        LocalDate yesterday = currentDate.minusDays(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String yesterdayString = yesterday.format(formatter);

        if(!CommonUtil.isNull(jsonObject.getString("payDate"))){
            yesterdayString = jsonObject.getString("payDate");
        }
//        String yesterdayString = "2024-06-27";

        String traceNo = UUID.randomUUID().toString();

        Result consMerchPayList = payConfigClientService.getConsMerchPayList(Long.valueOf(param));
        if(consMerchPayList.getCode()==200){
            List list = JSON.parseObject(JSON.toJSONString(consMerchPayList.getData()), List.class);
            setConsMerchPayReportsRequest setConsMerchPayReportsRequest = new setConsMerchPayReportsRequest();
            setConsMerchPayReportsRequest.setComId(param);
            setConsMerchPayReportsRequest.setPayDate(yesterdayString);
            setConsMerchPayReportsRequest.setMerchNoList(list);
            setConsMerchPayReportsRequest.setTraceNo(traceNo);
            Result result = payConfigClientService.setConsMerchPayReports(setConsMerchPayReportsRequest);
            if(result.getCode()==200&&result.getData()!=null){
               List xfMerchMoneyDayList = JSON.parseObject(JSON.toJSONString(result.getData()), List.class);
                AuthenticationRequest authenticationRequest = new AuthenticationRequest();
                ArrayList<TranInfo> arrayList = new ArrayList<>();

                authenticationRequest.setComId(Integer.valueOf(param));

                authenticationRequest.setTraceNo(traceNo);
                authenticationRequest.setUuid(traceNo);
                authenticationRequest.setTranDate(yesterdayString);

                for (Object object : xfMerchMoneyDayList) {
                    String jsonString = JSON.toJSONString(object);
                    EntityXfMerchMoneyDay xfMerchMoneyDay= JSON.parseObject(jsonString,EntityXfMerchMoneyDay.class);
                    if (xfMerchMoneyDay.getNowReceived() > 0 && xfMerchMoneyDay.getPayState() == 0) {
                        authenticationRequest.setMerNo(xfMerchMoneyDay.getMerchNoOut());
                        TranInfo tranInfo = new TranInfo();
                        tranInfo.setMerNo(xfMerchMoneyDay.getMerchNo());
                        tranInfo.setTranAmt(String.valueOf(xfMerchMoneyDay.getPayAmount()));
                        arrayList.add(tranInfo);
                    }
                }
                if(arrayList.size()>0){
                    authenticationRequest.setTranInfo(arrayList);
                    exposeapiClientService.confirmTrace(authenticationRequest);
                }
            }
        }
        XxlJobHelper.log("定时任务autoconfirmTrace处理每天自动分账的任务结束");

    }


    //定时任务处理打印任务
    @XxlJob("kitchenPrtTimer")
    public ReturnT<String> kitchenPrtTimer() throws Exception {
        XxlJobHelper.log("定时任务kitchenPrtTimer处理打印任务开始");
        payConfigClientService.kitchenPrtTimer();
        XxlJobHelper.log("定时任务kitchenPrtTimer处理打印任务结束");
        return ReturnT.SUCCESS;
    }



    public void init() {
        logger.info("init");
    }

    public void destroy() {
        logger.info("destroy");
    }


//    /**
//     * 3、命令行任务
//     */
//    @XxlJob("clearElkLog")
//    public void clearElkLogHandle() throws Exception {
//     public static void main(String[]  args) throws Exception {
//        String url = "http://47.107.69.158:9200/boutique-logstash-*/_delete_by_query";
//        Date date = DateUtil.getDateBefore(new Date(),31);
//
//        System.out.println(DateUtils.dateToStr(date));
//        String res = HttpClientUtil.httpClientPost(url,"{\n" +
//                "            \"query\": {\n" +
//                "            \"range\" : {\n" +
//                "                \"@timestamp\" : {\n" +
//                "                    \"gte\" : \"2023-03-01\",\n" +
//                "                            \"lte\" : \"2023-03-01\"\n" +
//                "                }\n" +
//                "            }\n" +
//                "        }\n" +
//                "        }");
//
//        System.out.println(res);
//    }

    //mq失败的重试
    @XxlJob("syncMqFailOrder")
    public void syncMqFailOrder() throws Exception {
        XxlJobHelper.log("mq失败的重试定时任务开始");
        String param = XxlJobHelper.getJobParam();
        payoperFeignService.syncMqFailOrder(param);
        XxlJobHelper.log("mq失败的重试定时任务结束");
    }


    //mq失败的重试
    @XxlJob("syncRefundOrder")
    public void syncRefundOrder() throws Exception {
        XxlJobHelper.log("mq退款查询定时任务开始");
        payoperFeignService.syncRefundOrder();
        XxlJobHelper.log("mq退款查询定时任务结束");
    }


    /**
     * @return  4.10定时任务更新过期账户为禁用（/accountDisabled）
     * @throws Exception
     */
    @XxlJob("accountDisabledTiming")
    public ReturnT<String> accountDisabledTiming() throws Exception {
        XxlJobHelper.log("定时任务accountDisabledTiming定时任务更新过期账户为禁用的任务开始");
        payConfigClientService.accountDisabled();
        XxlJobHelper.log("定时任务accountDisabledTiming定时任务更新过期账户为禁用的任务结束");
        return ReturnT.SUCCESS;
    }

     /**
     * @return  4.11定时任务账号到期提前三天发送短信(/accountExpiration)
     * @throws Exception
     */
    @XxlJob("accountExpiration")
    public ReturnT<String> accountExpiration() throws Exception {
        XxlJobHelper.log("定时任务accountExpirationTiming定时任务更新过期账户为禁用的任务开始");
        payConfigClientService.accountExpiration();
        XxlJobHelper.log("定时任务accountExpirationTiming定时任务更新过期账户为禁用的任务结束");
        return ReturnT.SUCCESS;
    }



    //订餐扣款
    @XxlJob("delayPay")
    public void delayPay()   {
        XxlJobHelper.log("delayPay定时任务开始");
        payoperFeignService.delayPay();
        XxlJobHelper.log("delayPay定时任务结束");
    }


    //取消订单
    @XxlJob("cancelDelayPay")
    public void cancelDelayPay()   {
        XxlJobHelper.log("delayPay定时任务开始");
        payoperFeignService.cancelDelayPay();
        XxlJobHelper.log("delayPay定时任务结束");
    }


    //定时记录当前人员的门禁状态
    @XxlJob("recordStudentKq")
    public void timerRecodeStudentKq()   {
        XxlJobHelper.log("recordStudentKq定时任务开始");
        String paramStr = XxlJobHelper.getJobParam();
        if(CommonUtil.isNull(paramStr)) return;
        humanClientService.saveUserRegion(Long.valueOf(paramStr));
        XxlJobHelper.log("recordStudentKq定时任务结束");
    }


    //定时记录当前人员的门禁状态
    @XxlJob("updateUserRegion")
    public void updateUserRegion()   {
        XxlJobHelper.log("updateUserRegion定时任务开始");
        String paramStr = XxlJobHelper.getJobParam();
        if(CommonUtil.isNull(paramStr)) return;
        humanClientService.updateUserRegion();
        XxlJobHelper.log("updateUserRegion定时任务结束");
    }

    @XxlJob("saveNotMeal")
    public void saveNotMeal(){
        XxlJobContext xxlJobContext = XxlJobContext.getXxlJobContext();
        String params = xxlJobContext.getJobParam();
        Long comId = 712L;
        try {
            JSONObject jsonObject = JSON.parseObject(params);
            comId = jsonObject.getLong("comId");;
        }catch (Exception e){

        }

        XxlJobHelper.log("saveNotMeal定时任务开始,单位Id是"+comId);
        AllPersonRequest request = new AllPersonRequest();
        List<Date> dateList = new ArrayList<>();
        dateList.add(new Date());
        dateList.add(cn.hutool.core.date.DateUtil.yesterday());

        Long finalComId = comId;
        dateList.forEach(date -> {
            request.setAreaNo(0L);
            request.setType(2);
            request.setComId(finalComId);
            request.setDate(date);
            request.setId(System.currentTimeMillis());
            this.mqSimpleClientService.allPerson(request);
        });


        XxlJobHelper.log("saveNotMeal定时任务结束");
    }




    @XxlJob("timerTransportOrder")
    public void timerTransportOrder(){
        XxlJobHelper.log("timerTransportOrder定时任务开始");
        payoperFeignService.timerTransportOrder();
        XxlJobHelper.log("timerTransportOrder定时任务结束");
    }

    @XxlJob("timerJFXM")
    public void timerJFXM(){
        XxlJobHelper.log("timerJFXM定时任务开始");
        String paramStr = XxlJobHelper.getJobParam();
        payConfigClientService.timerJFXM(Long.valueOf(paramStr));
        XxlJobHelper.log("timerJFXM定时任务结束");
    }


    @XxlJob("timerJFGzhMsg")
    public void timerJFGzhMsg(){
        XxlJobHelper.log("timerJFGzhMsg定时任务开始");
        String paramStr = XxlJobHelper.getJobParam();
        payConfigClientService.timerJFGzhMsg(Long.valueOf(paramStr));
        XxlJobHelper.log("timerJFGzhMsg定时任务结束");
    }

    @XxlJob("paymentTimingGzh")
    public void paymentTimingGzh(){
        XxlJobHelper.log("paymentTimingGzh定时任务开始");
        String paramStr = XxlJobHelper.getJobParam();
        payConfigClientService.paymentTimingGzh(Integer.valueOf(paramStr));
        XxlJobHelper.log("paymentTimingGzh定时任务结束");
    }

    @XxlJob("weimiAutoRefund")
    public void weimiAutoRefund(){
        XxlJobHelper.log("微米自动售卖机定时任务开始");
        String paramStr = XxlJobHelper.getJobParam();
        JSONObject jsonObject = JSON.parseObject(paramStr);
        Long comId = jsonObject.getLong("comId");
        JSONObject jsonObjectA = new JSONObject();
        jsonObjectA.put("comId",comId);
        this.payConfigClientService.autoRefund(jsonObjectA);
        XxlJobHelper.log("微米自动售卖机定时任务结束");
    }

//    @XxlJob("batchForecastOrder")
//    public void batchForecastOrder(){
//        XxlJobHelper.log("批量定时下单预订餐开始");
//        List<Long> comList = new ArrayList<>();
//        comList.add(1L);
//        comList.add(600L);
//
//        comList.forEach(comId->{
//            String paramStr = XxlJobHelper.getJobParam();
//            JSONObject jsonObject = JSON.parseObject(paramStr);
////            Long comId = jsonObject.getLong("comId");
//            String dateStr = jsonObject.getString("date");
//            Date date = new Date();
//            if(ObjectUtil.isNotEmpty(dateStr)){
//                try {
//                    date = cn.hutool.core.date.DateUtil.parseDate(dateStr);
//                }catch (Exception ignored){
//
//                }
//            }
//            BatchForecastOrderRequest batchForecastOrderRequest = new BatchForecastOrderRequest();
//            batchForecastOrderRequest.setComId(comId);
//            batchForecastOrderRequest.setMealDate(date);
//            this.payoperFeignService.batchForecastOrder(batchForecastOrderRequest);
//        });
//
//        XxlJobHelper.log("批量定时下单预订餐结束");
//    }


    @XxlJob("feature")
    public void feature(){
        XxlJobHelper.log("人脸特征值定时任务开始");
        humanClientService.feature();
        XxlJobHelper.log("人脸特征值定时任务结束");
    }


    @XxlJob("attendanceRuleTimer")
    public void attendanceRuleTimer(){
        XxlJobHelper.log("attendanceRuleTimer定时任务开始");
        accessClientService.attendanceRuleTimer();
        XxlJobHelper.log("attendanceRuleTimer定时任务结束");
    }

}
